﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace FluentUnity
{
    public static class Ensure
    {
        public static void IsNotNull<T>(Expression<Func<T>>  expression)
            where T : class
        {
            var argName = GetArgumentName(expression.Body);
            var argValue = expression.Compile().Invoke();
            if (argValue == null)
                throw new ArgumentNullException(argName);
        }

        private static string GetArgumentName(Expression body)
        {
            var bodyType = body.GetType();
            if(bodyType.Name != "FieldExpression" && bodyType.Name != "MemberExpression")
                throw new ArgumentException("Unable to determine parameter name from expression");

            var member = (MemberInfo)bodyType.GetProperty("Member").GetValue(body, null);
            return member.Name;
        }
    }
}
